//
//  UploadDataViewController.m
//  WideHelp
//
//  Created by ENERGY on 2018/8/14.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "UploadDataViewController.h"
#import "TZImagePickerController.h"
#import "UIPlaceHolderTextView.h"
#import "UploadDataCollectionViewCell.h"
#import "MJPhotoBrowser.h"
#import "MJPhoto.h"
#import <AssetsLibrary/ALAsset.h>
#import <Photos/Photos.h>
#import "UploadMessageView.h"
#define Border 10/WIDTH_6_SCALE
#define cellW (SCREEN_WIDTH - 4 * Border)/3
@interface UploadDataViewController ()<TZImagePickerControllerDelegate, MJPhotoBrowserDelegate, UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)UIView * headerView;
@property (nonatomic, strong)UIPlaceHolderTextView * textView;
@property (nonatomic, strong)UICollectionView * collectionView;
@property (nonatomic, strong)NSMutableArray * imageArray;
@property (nonatomic, strong)UIAlertController * alertController;
@property (nonatomic, strong)TZImagePickerController * imagePicker;
@property (nonatomic, strong)UIImagePickerController * imagePickerController;
@property (nonatomic, strong)MJPhotoBrowser * brower;
@end

@implementation UploadDataViewController(networking)


@end
@implementation UploadDataViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"上传资料";
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    //右侧消息按钮
    UIButton * naviRightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40/WIDTH_6_SCALE, 20/WIDTH_6_SCALE)];
    [naviRightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [naviRightBtn setTitle:@"提交" forState:UIControlStateNormal];
    [naviRightBtn addTarget:self action:@selector(naviRightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    naviRightBtn.titleLabel.font = DEF_FontSize_12;
    UIBarButtonItem * rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:naviRightBtn];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    //页面控件
    [self initViews];
}
- (void)initViews{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - BOTTOM_HEIGHT - NAVI_HEIGHT) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = getColor(@"f5f5f5");
    [self.view addSubview:self.tableView];
    //背景
    self.headerView = [[UIView alloc] init];
    self.headerView.backgroundColor = [UIColor whiteColor];
    //顶部分割线
    UIView * topLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1/WIDTH_6_SCALE)];
    topLineView.backgroundColor = getColor(@"eeeeee");
    [self.headerView addSubview:topLineView];
    //输入内容
    self.textView = [[UIPlaceHolderTextView alloc]initWithFrame:CGRectMake(16/WIDTH_6_SCALE, 17/WIDTH_6_SCALE + topLineView.bottom, SCREEN_WIDTH - 32/WIDTH_6_SCALE, 65/WIDTH_6_SCALE)];
    self.textView.backgroundColor = [UIColor whiteColor];
    self.textView.placeholder = @"请输入您的留言。留言将由博帮互助筛选后显示，对所有人可见。";
    [self.headerView addSubview:self.textView];
    //相册
    UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
    layout.minimumLineSpacing = 10/WIDTH_6_SCALE;
    layout.minimumInteritemSpacing = 10/WIDTH_6_SCALE;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.itemSize = CGSizeMake(cellW, cellW);
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(Border, CGRectGetMaxY(self.textView.frame) + 5/WIDTH_6_SCALE, SCREEN_WIDTH - 2*Border, cellW) collectionViewLayout:layout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.headerView addSubview:self.collectionView];
    [self.collectionView registerClass:[UploadDataCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([UploadDataCollectionViewCell class])];
    self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, CGRectGetMaxY(self.collectionView.frame) + 15/WIDTH_6_SCALE);
    self.tableView.tableHeaderView = self.headerView;
}
- (NSMutableArray *)imageArray{
    if (!_imageArray) {
        _imageArray = [NSMutableArray arrayWithArray:@[[UIImage imageNamed:@"fankui"]]];
    }return _imageArray;
}

- (UIImagePickerController *)imagePickerController{
    if (!_imagePickerController) {
        _imagePickerController = [[UIImagePickerController alloc]init];
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
    }return _imagePickerController;
}

-(UIAlertController *)alertController{
    if (!_alertController) {
        __weak typeof (self)weakSelf = self;
        _alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从图库选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            weakSelf.imagePicker = [[TZImagePickerController alloc]initWithMaxImagesCount:10 - self.imageArray.count delegate:self];
            weakSelf.imagePicker.allowPickingVideo = NO;
            
            weakSelf.imagePicker.allowTakePicture = NO;
            [self presentViewController:weakSelf.imagePicker animated:YES completion:nil];
        }];
        UIAlertAction *addPhoneAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:self.imagePickerController animated:YES completion:nil];
            }
            else
            {
                //  [self showMessage:@"当前设备无摄像头，请从相册获取"];
            }
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [photoAction setValue:getColor(@"584f60@") forKey:@"_titleTextColor"];
        [addPhoneAction setValue:getColor(@"584f60@") forKey:@"_titleTextColor"];
        [cancelAction setValue:getColor(@"584f60@") forKey:@"_titleTextColor"];
        [_alertController addAction:photoAction];
        [_alertController addAction:addPhoneAction];
        [_alertController addAction:cancelAction];
    }return _alertController;
}
- (void)getCollectionHeightForHeader{
    if (self.imageArray.count<4) {
        self.collectionView.frame = CGRectMake(Border, CGRectGetMaxY(self.textView.frame) + 5/WIDTH_6_SCALE, SCREEN_WIDTH - 2*Border, cellW);
    }
    if (self.imageArray.count<7 && self.imageArray.count>3) {
        self.collectionView.frame = CGRectMake(Border, CGRectGetMaxY(self.textView.frame) + 5/WIDTH_6_SCALE, SCREEN_WIDTH - 2*Border, cellW*2 + 10/WIDTH_6_SCALE);
    }
    if (self.imageArray.count<10 && self.imageArray.count>6) {
        self.collectionView.frame = CGRectMake(Border, CGRectGetMaxY(self.textView.frame) + 5/WIDTH_6_SCALE, SCREEN_WIDTH - 2*Border, cellW*3 + 20/WIDTH_6_SCALE);
    }
    self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, CGRectGetMaxY(self.collectionView.frame) + 15/WIDTH_6_SCALE);
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.imageArray.count < 10) {
        return self.imageArray.count;
    }return self.imageArray.count - 1;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UploadDataCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([UploadDataCollectionViewCell class]) forIndexPath:indexPath];
    cell.imageView.image = self.imageArray[indexPath.row];
    if (indexPath.row == self.imageArray.count - 1) {
        cell.deleteBtn.hidden = YES;
    }else{
        cell.deleteBtn.hidden = NO;
    }
    cell.deleteImgBlock = ^{
        [self photoBrowser:self.brower didDeletePhotoAtIndex:indexPath.row];
    };
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.imageArray.count < 10) {
        if (indexPath.row == self.imageArray.count - 1) {
            [self presentViewController:self.alertController animated:YES completion:nil];
            return;
        }
    }
    //1.创建图片浏览器
    MJPhotoBrowser *brower = [[MJPhotoBrowser alloc] init];
    self.brower = brower;
    //2.告诉图片浏览器显示所有的图片
    NSMutableArray *photos = [NSMutableArray array];
    for (int i = 0 ; i < self.imageArray.count - 1; i++) {
        //传递数据给浏览器
        MJPhoto *mjPhoto = [[MJPhoto alloc] init];
        mjPhoto.image = self.imageArray[i];
        UploadDataCollectionViewCell *cell = (UploadDataCollectionViewCell*)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        mjPhoto.srcImageView = cell.imageView; //设置来源哪一个UIImageView
        [photos addObject:mjPhoto];
    }
    brower.photos = photos;
    brower.isShowDeleteButton = YES;
    brower.delegate = self;
    //3.设置默认显示的图片索引
    brower.currentPhotoIndex = indexPath.row;
    //4.显示浏览器
    [brower show];
}
#pragma mark - MJPhotoBrowserDelegate
- (void)photoBrowser:(MJPhotoBrowser *)photoBrowser didDeletePhotoAtIndex:(NSInteger)index{
    if (index < self.imageArray.count) {
        UIImage *image = self.imageArray[index];
        [self.imageArray removeObject:image];
        [self getCollectionHeightForHeader];//判断header的高度
        [self.collectionView reloadData];
    }
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo{
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (self.imageArray.count >=10) {
        [self.view makeToast:@"您最多选择9张照片" duration:1 position:CSToastPositionCenter];
        return;
    }
    [self.imageArray insertObject:image atIndex:self.imageArray.count - 1];
    [_collectionView reloadData];
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        ALAssetsLibrary *library  = [[ALAssetsLibrary alloc] init];
        [library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
            if (error) {
                // TODO: error handling
            } else {
                [library  assetForURL:assetURL resultBlock:^(ALAsset *asset) {
                    //                    [self.selectPhotos addObject:asset];
                    //                    [_imageCollection reloadData];
                    [self.imageArray insertObject:image atIndex:self.imageArray.count - 1];
                    [self.collectionView reloadData];
                } failureBlock:^(NSError *error) {
                    
                }];
            }
        }];
    }
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos{
    if (self.imageArray.count + photos.count > 10) {
        [self.view makeToast:@"您最多选择9张照片" duration:1 position:CSToastPositionCenter];
        return;
    }
    [self.imageArray removeObjectAtIndex:self.imageArray.count - 1];
    [self.imageArray addObjectsFromArray:photos];
    [self.imageArray addObject:[UIImage imageNamed:@"fankui"]];
    [self getCollectionHeightForHeader];//判断header的高度
    [_collectionView reloadData];
}
#pragma mark - action
- (void)naviRightBtnClick:(UIButton *)sender{
    UploadMessageView * uploadMessageView = [[UploadMessageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - BOTTOM_HEIGHT - NAVI_HEIGHT)];
    [uploadMessageView show];
}
@end
